<?php

namespace app\admin\controller\dahuinew;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;

/**
 * 代理记账月记录管理
 *
 * @icon fa fa-circle-o
 */
class Dljzmonth extends Backend
{
    
    /**
     * Dljzmonth模型对象
     * @var \app\admin\model\dahuinew\Dljzmonth
     */
    protected $model = null;

    protected $noNeedRight = ['changezcstatus', 'changesbstatus', 'index2', 'pljnstatus0', 'pljnstatus1', 'plzcstatus0', 'plzcstatus1'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dahuinew\Dljzmonth;
        $this->view->assign("sbztList", $this->model->getSbztList());
        $this->view->assign("zcztList", $this->model->getZcztList());

        $this->assignconfig('jingban', $this->auth->check('dahuinew/dljzyw/jingban'));

        $u = AuthGroupAccess::where('uid', $this->auth->id)->find();
        if ($u->group_id <= 2 || $u->group_id == 13) {
            $this->assignconfig('isadmin', true);
            $this->view->assign("isadmin", true);
        } else {
            $this->assignconfig('isadmin', false);
            $this->view->assign("isadmin", false);
        }
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $thismonth = date("Y-m");

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $u = AuthGroupAccess::where('uid', $this->auth->id)->find();
            if ($u->group_id != 15) {
                $total = $this->model
                    ->with(['dljzyw'])
                    ->where($where)
                    ->where('sbyf', '<=', $thismonth)
                    ->where('dljzyw.htend2', '>', $filter['sbyf'])
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['dljzyw'])
                    ->where($where)
                    ->where('sbyf', '<=', $thismonth)
                    ->where('dljzyw.htend2', '>', $filter['sbyf'])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $total = $this->model
                    ->with(['dljzyw'])
                    ->where($where)
                    ->where('sbyf', '<=', $thismonth)
                    ->where('dljzyw.htend2', '>', $filter['sbyf'])
                    ->where('dljzyw.admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['dljzyw'])
                    ->where($where)
                    ->where('sbyf', '<=', $thismonth)
                    ->where('dljzyw.htend2', '>', $filter['sbyf'])
                    ->where('dljzyw.admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            $yje_znum = 0;
            foreach ($list as &$row) {
                $row['yje'] = 0; //月金额
                $yuenum = $this->model
                    ->where('dljzyw_id', $row["dljzyw_id"])
                    ->count();
                if ($yuenum > 0) {
                    $row['yje'] = floatval($row['dljzyw']['htje']) / $yuenum;
                }
                $yje_znum += $row['yje'];
                $row['yje'] = sprintf("%.2f", $row['yje']);
            }
            $list = collection($list)->toArray();
//            $result = array("total" => $total, "rows" => $list);
            $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $yje_znum)]);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index2()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $where1 = " (sbzt = '已办理' or dljzyw.zczt = '已停止')";
            $u = AuthGroupAccess::where('uid', $this->auth->id)->find();
            if ($u->group_id != 15) {
                $total = $this->model
                    ->with(['dljzyw'])
                    ->where($where)
//                    ->where($where1)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['dljzyw'])
                    ->where($where)
//                    ->where($where1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $total = $this->model
                    ->with(['dljzyw'])
                    ->where($where)
//                    ->where($where1)
                    ->where('dljzyw.admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['dljzyw'])
                    ->where($where)
//                    ->where($where1)
                    ->where('dljzyw.admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            foreach ($list as $row) {


            }
            $list = collection($list)->toArray();

//            $thismonth = date("Y-m");
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            if (isset($filter['dljzyw.htstart'])) {
                $sql = "select sum(htje) as num from fa_dahuinew_dljzyw where htstart = '{$filter['dljzyw.htstart']}' ";
                $money = Db::query($sql);
                $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $money[0]['num'])]);
            } else {
                $result = array("total" => $total, "rows" => $list, "extend" => ['money' => ""]);
            }

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();

                    if (isset($params['dljzyw.remarks1'])) {
                        $dd = \app\admin\model\dahuinew\Dljzyw::get($row->dljzyw_id);
                        $dd->remarks1 = $params['dljzyw.remarks1'];
                        $dd->save();
                    }

                    if (isset($params['dljzyw.remarks2'])) {
                        $dd = \app\admin\model\dahuinew\Dljzyw::get($row->dljzyw_id);
                        $dd->remarks2 = $params['dljzyw.remarks2'];
                        $dd->save();
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 转出状态
     */
    //http://dahui.test/admin/dahuinew/dljzmonth/changezcstatus
    public function changezcstatus($ids = null)
    {
        $row = \app\admin\model\dahuinew\Dljzmonth::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->zczt == '未办理') {
            $row->zczt = '已办理';

            $dd = \app\admin\model\dahuinew\Dljzyw::get($row->dljzyw_id);
            $dd->htend2 = date("Y-m");
            $dd->save();

        } else if ($row->zczt == '已办理') {
            $row->zczt = '未办理';
        }
        $row->jbry = $this->auth->nickname;
        $row->save();
        $this->success("转出状态修改成功", null, ['zczt' => $row->zczt]);

    }


    /**
     * 申报状态
     */
    //http://dahui.test/admin/dahuinew/dljzmonth/changesbstatus
    public function changesbstatus($ids = null)
    {
        $row = \app\admin\model\dahuinew\Dljzmonth::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->sbzt == '未办理') {
            $row->sbzt = '已办理';
        } else if ($row->sbzt == '已办理') {
            $row->sbzt = '未办理';
        }
        $row->jbry = $this->auth->nickname;
        $row->save();
        $this->success("申报状态修改成功", null, ['sbzt' => $row->sbzt]);

    }

    //批量转出状态-未办理
    public function plzcstatus0($ids = null)
    {
        $list = \app\admin\model\dahuinew\Dljzmonth::where('id', 'in', $ids)->select();

        foreach ($list as $row) {
            $row->zczt = '未办理';
            $row->jbry = $this->auth->nickname;
            $row->save();

        }
        $this->success();
    }

    //批量转出状态-已办理
    public function plzcstatus1($ids = null)
    {
        $list = \app\admin\model\dahuinew\Dljzmonth::where('id', 'in', $ids)->select();

        foreach ($list as $row) {
            $row->zczt = '已办理';
            $row->jbry = $this->auth->nickname;
            $row->save();

        }
        $this->success();
    }

    //批量缴纳状态-未办理
    public function pljnstatus0($ids = null)
    {
        $list = \app\admin\model\dahuinew\Dljzmonth::where('id', 'in', $ids)->select();

        foreach ($list as $row) {
            $row->sbzt = '未办理';
            $row->jbry = $this->auth->nickname;
            $row->save();

        }
        $this->success();
    }

    //批量缴纳状态-已办理
    public function pljnstatus1($ids = null)
    {
        $list = \app\admin\model\dahuinew\Dljzmonth::where('id', 'in', $ids)->select();

        foreach ($list as $row) {
            $row->sbzt = '已办理';
            $row->jbry = $this->auth->nickname;
            $row->save();

        }
        $this->success();
    }

}
